import React, { Component } from "react";
import { Tabs, Table, Button, Input, message, Modal, Checkbox } from "antd";
import Recharge from "./Recharge";
import Withdraw from "./Withdraw";
import TransfPopup from "../../../components/transfPopup";
import TranAccount from "./TranAccount";

import "./property.css";

const TabPane = Tabs.TabPane;
const Search = Input.Search;

class Property extends Component {
  state = {
    modalTit: "",
    showModal: false,
    actionType: "",
    availableC2c: 0,
    handleCoin: null,
    handleVolume: "",
    c2cData: null,
    normalData: null,
    normalAllData: null,
    expandedRowKey: "",
    expendedFlag: "",
    currencyName: "",
    checked: false,
    freezeData: [],
    popup: ""
  };

  request = window.request;

  componentWillMount() {
    this.getNormalData();
  }

  inputVolume = e => {
    let value = e.target.value;
    if (/^\d*\.{0,1}\d{0,8}$/.test(value) && value.length < 16) {
      this.setState({ handleVolume: value });
    }
  };

  tabChange = key => {
    if (key === "routine") {
      this.getNormalData();
      this.setState({ currencyName: "", expandedRowKey: '' });
    } else if (key === "c2c") {
      this.getC2cData();
    } else if (key === "freeze") {
      this.getFreezeList();
    }
  };
  getC2cData = () => {
    this.request("/offline/volume/list", {
      method: "GET"
    }).then(json => {
      if (json.code === 10000000) {
        const c2cData = json.data.map(item => {
          item.key = item.coinId;
          item.volume = item.volume || "0.00";
          item.advertVolume = item.advertVolume || "0.00";
          item.lockVolume = item.lockVolume || "0.00";
          item.bailVolume = item.bailVolume || "0.00";
          item.totalPrice = (
            Number(item.volume) +
            Number(item.advertVolume) +
            Number(item.lockVolume) +
            Number(item.bailVolume)
          ).toFixed(8);
          return item;
        });
        this.setState({ c2cData });
      } else {
        message.error(json.msg);
      }
    });
  };
  getNormalData = () => {
    this.request("/coin/volume/list", {
      method: "GET"
    }).then(json => {
      if (json.code === 10000000) {
        const normalAllData = json.data.map(item => {
          let totalPrice = 0;
          let {
            id,
            name,
            volume,
            lockVolume,
            bailVolume,
            tokenStatus,
            withdrawFee,
            withdrawFeeType,
            withdrawMaxVolume,
            withdrawMinVolume
          } = item;
          volume = volume || "0.00";
          lockVolume = lockVolume || "0.00";
          bailVolume = bailVolume || "0.00";
          totalPrice = (
            Number(volume) +
            Number(lockVolume) +
            Number(bailVolume)
          ).toFixed(8);
          withdrawFee = withdrawFee || "0.00";
          return {
            ...item,
            key: id,
            id,
            name,
            volume,
            lockVolume,
            bailVolume,
            totalPrice,
            tokenStatus,
            withdrawFee,
            withdrawFeeType,
            withdrawMaxVolume,
            withdrawMinVolume,
          };
        });
        const checked = localStorage.getItem("zeroChecked");
        let normalData = normalAllData;
        if (checked && checked === "true") {
          normalData = normalAllData.filter(item => {
            return item.volume > 0;
          });
          this.setState({ normalData, normalAllData, checked: true });
        } else {
          this.setState({ normalData, normalAllData, checked: false });
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  // 获取冻结账户
  getFreezeList = () => {
    this.request("/mk2/user/alllock", {
      method: "GET"
    }).then(json => {
      if (json.code === 10000000) {
        const freezeData = json.data.map((item, index) => {
          item.key = index;
          return item;
        });
        this.setState({ freezeData });
      } else {
        message.error(json.msg);
      }
    });
  };

  // 获取充币地址
  getRechargeAddress = (coinId) => {
    this.request('/coin/user/address/' + coinId, {
      method: 'GET'
    }).then(json => {
      if (json.code === 10000000) {
        const { tag, address } = json.data;
        let { normalData } = this.state;
        normalData = normalData.map((item) => {
          if (coinId === item.id) {
            item.address = address;
            item.tag = tag;
          }
          return item;
        });

        this.setState({ normalData });
      }else{
        message.destroy();
        message.error(json.msg);
      }
    });
  }

  // 获取提币地址列表
  getWithdrawAddress = (coinId) => {
    this.request('/withdraw/address/list/' + coinId, {
      method: 'GET'
    }).then(json => {
      if (json.code === 10000000) {
        let addressHistory = json.data.map(item => {
          const { address } = item;
          return address;
        });
        let { normalData } = this.state;
        normalData = normalData.map((item) => {
          if (coinId === item.id) {
            item.addressHistory = addressHistory;
          }
          return item;
        });
        this.setState({ normalData });
      }
    });
  }

  handleRecharge = record => {
    const { id } = record;
    if (!record.address) {
      this.getRechargeAddress(id);
    }
    this.setState({
      expandedRowKey: record.key,
      expendedFlag: "recharge"
    });
  };
  handleWithdraw = record => {
    const { addressHistory, id } = record;
    if (!addressHistory) {
      this.getWithdrawAddress(id);
    }
    this.setState({
      expandedRowKey: record.key,
      expendedFlag: "withdraw"
    });
  };

  handleSearch = e => {
    let value = e.target.value;
    if (value.length < 16) {
      let { normalAllData, checked } = this.state;
      let normalData = normalAllData;
      if (checked) {
        normalData = normalAllData.filter(item => {
          return item.volume > 0;
        });
      }
      let target = value.toUpperCase();
      normalData = normalData.filter(item => {
        return item.name.indexOf(target) > -1;
      });
      this.setState({ currencyName: value, normalData });
    }
  };

  zeroChange = e => {
    const checked = e.target.checked;
    const { normalAllData, currencyName } = this.state;
    const target = currencyName.toUpperCase();
    let normalData = normalAllData.filter(item => {
      return item.name.indexOf(target) > -1;
    });
    if (checked) {
      normalData = normalData.filter(item => {
        return item.volume > 0;
      });
    }
    this.setState({ checked, normalData });
    localStorage.setItem("zeroChecked", checked);
  };

  handleTransfer = record => {
    const coinProps = {
      coinId: record.coinId,
      symbol: record.symbol
    };
    this.setState({
      popup: (
        <TransfPopup
          {...coinProps}
          onCancel={this.closeModal}
          onOK={() => {
            this.closeModal();
            this.getC2cData();
          }}
        />
      )
    });
  };

  closeModal = () => {
    this.setState({ popup: "" });
  };

  allTurnClick = () => {
    const { availableC2c } = this.state;
    if (availableC2c > 0) {
      this.setState({ handleVolume: availableC2c });
    }
  };

  tranAccount = record => {
    this.setState({
      popup: (
        <TranAccount
          {...record}
          onCancel={this.closeModal}
          onOk={() => {
            this.closeModal();
            this.getC2cData();
          }}
        />
      )
    });
  };

  render() {
    const {
      c2cData,
      normalData,
      expandedRowKey,
      expendedFlag,
      currencyName,
      checked,
      freezeData,
      popup
    } = this.state;

    const routineColumns = [
      {
        title: "资金名称",
        dataIndex: "name",
        key: "name",
        render: text => {
          const type = text.toLowerCase();
          return (
            <div>
              <span className={`currency-logo ${type}`} />
              {text}
            </div>
          );
        }
      },
      {
        title: "可用资金",
        dataIndex: "volume",
        key: "volume",
        render: text => {
          return (
            <div className="available-col">
              <i className="iconfont icon-qianbao" /> {Number(text).toFixed(8)}
            </div>
          );
        }
      },
      {
        title: "挂单金额",
        dataIndex: "lockVolume",
        key: "lockVolume",
        render: text => {
          return <div>{Number(text).toFixed(8)}</div>;
        }
      },
      {
        title: "总计",
        dataIndex: "totalPrice",
        key: "totalPrice",
        render: text => {
          return <div>{text}</div>;
        }
      },
      {
        title: "操作",
        dataIndex: "action",
        key: "action",
        render: (text, record) => (
          <div className="property-action">
            {(record.tokenStatus * 1 === 1 || record.tokenStatus * 1 === 2) && (
              <Button
                type="primary"
                onClick={() => {
                  this.handleRecharge(record);
                }}
              >
                充币
              </Button>
            )}
            {(record.tokenStatus * 1 === 1 || record.tokenStatus * 1 === 3) && (
              <Button
                type="primary"
                onClick={() => {
                  this.handleWithdraw(record);
                }}
              >
                提币
              </Button>
            )}
          </div>
        )
      }
    ];

    const c2cColumns = [
      {
        align: "center",
        title: "资金名称",
        dataIndex: "symbol",
        key: "symbol",
        render: (text, record) => {
          const type = text.toLowerCase();
          return (
            <div>
              <span className={`currency-logo ${type}`} />
              {text}
            </div>
          );
        }
      },
      {
        align: "center",
        title: "可用资金",
        dataIndex: "volume",
        key: "volume",
        render: (text, record) => {
          return (
            <div className="available-col">
              <i className="iconfont icon-qianbao" /> {Number(text).toFixed(8)}
            </div>
          );
        }
      },
      {
        align: "center",
        title: "广告冻结",
        dataIndex: "advertVolume",
        key: "advertVolume",
        render: text => {
          return <div>{Number(text).toFixed(8)}</div>;
        }
      },
      {
        align: "center",
        title: "交易冻结",
        dataIndex: "lockVolume",
        key: "lockVolume",
        render: text => {
          return <div>{Number(text).toFixed(8)}</div>;
        }
      },
      {
        align: "center",
        title: "手续费预备金",
        dataIndex: "bailVolume",
        key: "bailVolume",
        render: text => {
          return <div>{Number(text).toFixed(8)}</div>;
        }
      },
      {
        align: "center",
        title: "总计",
        dataIndex: "totalPrice",
        key: "totalPrice",
        render: text => {
          return <div>{Number(text).toFixed(8)}</div>;
        }
      },
      {
        align: "center",
        title: "操作",
        dataIndex: "action",
        key: "action",
        render: (text, record) => {
          const { isChangeAccount } = record;
          return (
            <div className="property-action" style={{ display: "flex" }}>
              <Button
                type="primary"
                onClick={() => {
                  this.handleTransfer(record);
                }}
              >
                资产互转
              </Button>
              {isChangeAccount === "0" && (
                <Button
                  style={{ marginLeft: 4 }}
                  type="primary"
                  onClick={() => {
                    this.tranAccount(record);
                  }}
                >
                  转账
                </Button>
              )}
            </div>
          );
        }
      }
    ];

    const freezeColumns = [
      {
        title: "币种",
        dataIndex: "coinSymbol",
        key: "coinSymbol"
      },
      {
        title: "冻结类型",
        dataIndex: "memberType",
        key: "memberType",
        render: text => {
          let myText = "";
          switch (text) {
            case "1":
              myText = "初始冻结";
              break;
            case "2":
              myText = "节点人";
              break;
            case "3":
              myText = " 合伙人";
              break;
            default:
              myText = "";
          }
          return <div>{myText}</div>;
        }
      },
      {
        title: "冻结总额",
        dataIndex: "lockVolume",
        key: "lockVolume"
      },
      {
        title: "累计已释放数量",
        dataIndex: "releaseVolume",
        key: "releaseVolume"
      }
    ];

    return (
      <div className="user-cont property">
        <Tabs defaultActiveKey="routine" onChange={this.tabChange}>
          <TabPane tab="常规账户" key="routine">
            <header className="property-header clear">
              <h2 className="pull-left">我的资金一览表</h2>
              <div className="header-search">
                <Checkbox onChange={this.zeroChange} checked={checked}>
                  隐藏资产为0的币种
                </Checkbox>
                ,
                <Search
                  value={currencyName}
                  onChange={this.handleSearch}
                  style={{ width: 100 }}
                />
              </div>
            </header>
            <Table
              dataSource={normalData}
              columns={routineColumns}
              pagination={false}
              expandedRowRender={record => {
                if (expendedFlag === "recharge") {
                  return <Recharge {...record} />;
                } else if (expendedFlag === "withdraw") {
                  return <Withdraw {...record} />;
                } else {
                }
              }}
              expandedRowKeys={[expandedRowKey]}
            />
          </TabPane>
          <TabPane tab="C2C账户" key="c2c">
            <header className="property-header clear">
              <h2 className="pull-left">我的资金一览表</h2>
              <ul className="pull-right">
                <li>&nbsp;</li>
                {/* <li className="assets-estimate">资产估算：0.000000 BTC</li> */}
              </ul>
            </header>
            <Table
              dataSource={c2cData}
              columns={c2cColumns}
              pagination={false}
            />
          </TabPane>
          <TabPane tab="冻结账户" key="freeze">
            <Table
              loading={!freezeData}
              dataSource={freezeData}
              columns={freezeColumns}
              pagination={false}
            />
          </TabPane>
        </Tabs>
        {popup}
      </div>
    );
  }
}

export default Property;
